<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <el-button
      v-bind="options"
      @click="() => eventHandler.trigger('点击事件')"
    >
      <cc-icon
        v-if="prefixIconId"
        :iconId="prefixIconId"
        style="margin-right: 5px;"
      />
      {{ currValue }}
      <cc-icon
        v-if="suffixIconId"
        :iconId="suffixIconId"
        style="margin-left: 5px;"
      />
    </el-button>
  </div>
</template>

<script setup>
import { ref, computed, inject, getCurrentInstance, nextTick, onMounted } from 'vue';
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  node: Object
});

const initializing = ref(true);
const currNode = ref(props.node);
const currValue = ref('');
const prefixIconId = ref('');
const suffixIconId = ref('');
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const init = async(styleId) => {
  initializing.value = true;
  currValue.value = null;
  visual.initStyle(currNode.value, styleId);

  const compStyle = currNode.value.currCompStyle || {};
  currValue.value = compStyle['buttonName'] || '';
  prefixIconId.value = compStyle['prefixIcon'] || '';
  suffixIconId.value = compStyle['suffixIcon'] || '';

  await nextTick(() => initializing.value = false);
};

const options = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};
  const options = {};
  visual.addIfNotNull(options, compStyle, 'size');
  visual.addIfNotNull(options, compStyle, 'type');
  visual.addIfNotNull(options, compStyle, 'style');
  visual.addIfNotNull(options, compStyle, 'label');
  visual.addIfNotNull(options, compStyle, 'plain');
  visual.addIfNotNull(options, compStyle, 'text');
  visual.addIfNotNull(options, compStyle, 'round');
  visual.addIfNotNull(options, compStyle, 'circle');
  visual.addIfNotNull(options, compStyle, 'disabled');
  return options;
});

const getData = () => {
  return {
    value: currValue.value
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  await eventHandler.trigger('初始化事件');
});

defineExpose({ getData, changeStyle, refresh });
</script>